#include "rowlabel.h"
#include <allegro5/allegro5.h>
#include <allegro5/allegro_primitives.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include "font.h"
#include "skin.h"
using namespace std;

RowLabel::RowLabel(int count, int charWidth, Font *pFont, 
		   Point start, int height, int highlight, Skin *pSkin)
: m_count(count), m_charWidth(charWidth), m_pFont(pFont), 
  m_start(start), m_height(height), m_offset(0), m_highlight(highlight),
  m_pSkin(pSkin) {
}

int RowLabel::count() {
     return m_count;
}

void RowLabel::setCount(int count) {
     m_count = count;
}

void RowLabel::paint() {
     Rect lr = rect();
     int linex = lr.x() + lr.width() - RowLabel::SeparatorThickness;
     // draw numbers
     Rect r = rect();
     const int pad = RowLabel::Padding;
     r.setX(r.x() + pad);
     int visrows = ceil((float)r.height() / (float)m_pFont->height());
     // setup colors
     ALLEGRO_COLOR white = al_map_rgb(255,255,255);
     ALLEGRO_COLOR highlight = m_pSkin->color(Skin::HighlightColor2);
     ostringstream s;
     s << hex << uppercase;
     r.setWidth(m_pFont->width()*m_charWidth);
     for (int i=0; i<visrows && i+m_offset<m_count; i++) {
	  r.setHeight(m_pFont->height());
	  if (r.y() + r.height() > m_start.y() + m_height)
	       r.setHeight(m_start.y() + m_height - r.y());
	  s.clear();
	  s.str("");
	  s << setw(m_charWidth) << setfill('0') << m_offset+i+1;
	  if (m_highlight && !((m_offset + i) % m_highlight))
	       al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, highlight);
	  else
	       al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, white);
	  m_pFont->print(s.str(), r);
	  r.setY(r.y()+m_pFont->height());
     }
     al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, white);
     // draw separator line
     al_draw_line(linex, m_start.y(), linex, m_start.y() + m_height,
		  al_map_rgb(255,255,255), RowLabel::SeparatorThickness);
}

Rect RowLabel::rect() {
     const int pad = RowLabel::Padding;
     int w = m_charWidth * m_pFont->width() + RowLabel::SeparatorThickness + pad * 2;
     return Rect(m_start.x(), m_start.y(), w, m_height);
}

void RowLabel::setOffset(int offset) {
     m_offset = offset;
}

void RowLabel::setStart(Point start) {
     m_start = start;
}

void RowLabel::setHeight(int height) {
     m_height = height;
}

int RowLabel::highlight() {
     return m_highlight;
}

void RowLabel::setHighlight(int highlight) {
     m_highlight = highlight;
}

void RowLabel::setFont(Font *pFont) {
     m_pFont = pFont;
}
